package com.ytb.utils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import java.security.SecureRandom;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

public class MybatisPlusUtils {

    /**
     * 随机查询
     * @param mapper 持久层DAO
     * @param limit  随机条数
     * @return java.util.List<T>
     */
    public static <T> List<T> getAny(BaseMapper<T> mapper, T condition, Integer limit) {
        LambdaQueryWrapper<T> wrapper = Wrappers.lambdaQuery(condition);
        Integer total = mapper.selectCount(wrapper);
        if (limit == null || limit <= 0 || total == 0) {
            return Collections.emptyList();
        }
        List<T> list = Optional.of(limit).filter(l -> l > total).map(l -> mapper.selectList(wrapper)).orElseGet(() -> mapper.selectList(wrapper.last("LIMIT " + new SecureRandom().nextInt(total - (limit - 1)) + "," + limit)));
        Collections.shuffle(list);
        return list;
    }
}
